// main.js
import React, { useState, useEffect } from 'react';
import {
  createFromIconfontCN, ClockCircleOutlined
} from '@ant-design/icons';

import { Button, Input, Divider, Select, Spin, Tabs, List, Typography, Modal } from 'antd';
import { addkey_for_mxdata, convertISODateTimeToYYYYMMDDHHMMSS, fetchsync_util, openNotification_util } from './shipSRM/util/util.js'
import { useHistory } from 'react-router-dom';
import mainpage_bg from '../img/shipSRM/mainpage_bg.png'
import './mainpage.css'
import Highlighter from 'react-highlight-words';
import useStore from './useStore.js'
import { dropByCacheKey } from 'react-router-cache-route';
import { use_button_config } from './shipSRM/sys/use_button_config.js';
import { getRouteConfig } from './routeConfig.js';

const { Search } = Input

var storage = window.localStorage;
const { Option } = Select;

const IconFont = createFromIconfontCN({
  scriptUrl: 'http://111.77.154.58:2233/icon.js',
});


const Mainpage = () => {

  const history = useHistory();

  const [scList, setScLisst] = useState([])


  const [menuList, setMenuList] = useState([])

  const [menuRightList, setMenuRightList] = useState([])

  const [searchText, setSearchText] = useState('')

  const { setnowroute, collapsed, needrefreshsclist } = useStore();

  const [zcbList, setZcbList] = useState([]) //注册申请
  const [gysbgList, setGysbgList] = useState([]) //供应商变更
  const [gysybList, setGysybList] = useState([]) //供应商应标
  const [gysjbList, setGysjbList] = useState([]) //供应商竟标
  const [zhDbList, setZhDbList] = useState([]) //租户待办
  const [glDbList, setGlDbList] = useState([]) //管理待办
  const [fbTzggList, setFbTzggList] = useState([]) //已发布的通知公告
  const [open, setOpen] = useState(false);
  const [open2, setOpen2] = useState(false);
  const [previewContent, setPreviewContent] = useState("");

  const tonormal = (route) => {
    history.push(route)

  }


  const handleClick = (item, e) => {
    //  console.log(item,"111");
    e.stopPropagation()
    if (item.sfsc != '是') {

      updateMenuList("是", item.cdbh, item.cdmc)
      queryMenuList()
    }
    else {
      updateMenuList("否", item.cdbh, item.cdmc)
      queryMenuList()
    }
  }

  const queryMenuList = async () => {
    let rtdata = await fetchsync_util("/admin/sys/queryMenuList", 'POST', { ygbh: storage.ygbh }, "json")
    const itemArray = []
    for (let item of rtdata.yjcdList) {
      let itemObj = { label: item.cdmc, key: item.id, route: item.cdly, icon: <IconFont type={item.cdtb} />, theme: 'light' }
      var childrenArray = []
      for (let itemChild of rtdata.ejcdList) {
        if (item.cdmc == itemChild.parent_mc) {
          let itemObj2 = {
            label: <div id={itemChild.id}><Highlighter highlightStyle={{
              backgroundColor: 'yellow', padding: 0,
            }}
              searchWords={[searchText]} autoEscape textToHighlight={itemChild.cdmc} /><div className="icon-button" style={{ position: 'absolute', right: '1vw', top: '0', zIndex: "200", width: '3vw', textAlign: 'center' }}
                onClick={e => { handleClick(itemChild, e) }}><IconFont
                  type={itemChild.sfsc != '是' ? "shoucang" : "yellowStar"}></IconFont></div>
            </div>, key: itemChild.cdmc, route: itemChild.cdly, theme: 'light', id: itemChild.id
          }
          childrenArray.push(itemObj2)
        }
      }
      childrenArray.length == 0 ? 1 : itemObj.children = childrenArray
      itemArray.push(itemObj)

    }
    //console.log(itemArray)
    setMenuList(itemArray)
    var menuRightData = []
    menuRightData.push(...rtdata.yjcdList)
    menuRightData.push(...rtdata.ejcdList)
    menuRightData.sort((a, b) => a.cdpx - b.cdpx);
    setMenuRightList(menuRightData)
  }


  const updateMenuList = async (sfsc, cdqx, cdmc) => {
  }
  const queryScList = async () => {
    let rtdata = await fetchsync_util("/admin/sys/queryScList", 'POST', { ygbh: storage.ygbh }, "json")
    var itemArray = []
    var itemObj = { label: "收藏夹", key: '1', icon: <IconFont type="shoucang" />, theme: 'light' }
    var childrenArray = []
    // console.log(rtdata)
    for (let item of rtdata) {
      let itemObj2 = {
        label: <div id={item.id}><Highlighter highlightStyle={{
          backgroundColor: 'yellow', padding: 0,
        }}
          searchWords={[searchText]} autoEscape textToHighlight={item.cdmc} /><div className="icon-button" style={{ position: 'absolute', right: '1vw', top: '0', zIndex: "200", width: '3vw', textAlign: 'center' }}
            onClick={e => { handleClick(item, e) }}><IconFont
              type={item.sfsc != '是' ? "shoucang" : "yellowStar"}></IconFont></div>
        </div>, key: item.id, route: item.cdly, cdmc: item.cdmc, icon: <IconFont type={item.cdtb} />, theme: 'light'
      }
      childrenArray.push(itemObj2)
    }
    childrenArray.length == 0 ? itemObj.children = [] : itemObj.children = childrenArray
    itemArray.push(itemObj)
    // console.log(itemArray)
    setScLisst(itemArray)
  }

  const queryTaskList = async () => {
    let rtdata = await fetchsync_util("/admin/sys/query_db_task", 'POST', {}, "json")
    // console.log(rtdata)
    setZcbList(addkey_for_mxdata(rtdata.resultdata.zcbData))
    setGysbgList(addkey_for_mxdata(rtdata.resultdata.gysbgData))
    //管理待办
    let glDblist=rtdata.resultdata.zcbData.concat(rtdata.resultdata.gysbgData).concat(rtdata.resultdata.pbdata).
    concat(rtdata.resultdata.lxdata).concat(rtdata.resultdata.jjzcdata).concat(rtdata.resultdata.zbfpdata)
    setGlDbList(
       addkey_for_mxdata(glDblist.sort((a,b)=>new Date(b.create_time)-new Date(a.create_time)))
    )
    //租户待办
    let zhDblist=rtdata.resultdata.gysybData.concat(rtdata.resultdata.gysdjbData)
    .concat(rtdata.resultdata.gysjbzData)
    .concat(rtdata.resultdata.gystbdata).concat(rtdata.resultdata.gyszbdata).concat(rtdata.resultdata.gysxjdata)
    console.log(zhDblist, "zhDblist");
    setZhDbList(
       addkey_for_mxdata(zhDblist.sort((a,b)=>new Date(b.create_time)-new Date(a.create_time)))
    )
    // setGysybList(addkey_for_mxdata(rtdata.resultdata.gysybData))
    // setGysjbList(addkey_for_mxdata(rtdata.resultdata.gysjbData))
  }

  const queryFbTzggList = async () => {
    let rtdata = await fetchsync_util("/admin/sys/query_fb_tzgg", 'POST', {}, "json")
    setFbTzggList(addkey_for_mxdata(rtdata.resultdata.rtdata.map(item => {
      item.fbsj = item.fbsj ? convertISODateTimeToYYYYMMDDHHMMSS(item.fbsj) : ""
      return item
    })))
  }

  const queryIfexistGyswh = async () => {
    let rtdata = await fetchsync_util("/admin/sys/ifexist_gyswh", 'POST', {ygbh:storage.ygbh}, "json")
    console.log(rtdata, "11121313");
    if (rtdata.resultdata.length > 0 && rtdata.resultdata[0].gyswhzt != "已维护") {
      setOpen2(true)
      storage.pre_gys_item = JSON.stringify({ data: rtdata.resultdata[0], type: "edit" })
    }
  }

  const queryAnpzByJs = async () => {
    let rtdata = await fetchsync_util("/admin/sys/query_anpz_byjs", 'POST', { js: storage.js }, "json")
    if (rtdata?.resultdata?.formdata?.anpz) {
      let anpz = JSON.parse(rtdata.resultdata.formdata.anpz)
      let newanpz = []
      let buttonConfig = use_button_config()
      buttonConfig.forEach(Item => {
        let obj = anpz.find(item => item.key == Item.key)
        let czAnpz = {}
        let listAnpz = {}
        //
        Item.options.filter(item2 => item2.sfczq == true).forEach(objItem => {
          if (obj && obj.checkedList.some(item2 => item2 == objItem.value)) {
            czAnpz[objItem.value] = true
          }
        })
        Item.options.filter(item2 => item2.sfczq == false).forEach(objItem => {
          if (obj && obj.checkedList.some(item2 => item2 == objItem.value)) {
            listAnpz[objItem.value] = true
          }
        })

        newanpz.push({
          key: Item.key,
          czAnpz,
          listAnpz
        })
      })
      console.log(newanpz, "newanpz");
      storage.anpz = JSON.stringify(newanpz)
    }
  }

  useEffect(() => {
    queryMenuList()
    queryScList()
    queryTaskList()
    queryFbTzggList()
    queryIfexistGyswh()
    queryAnpzByJs()
  }, [])

  const handleGyswh = () => {
    setOpen2(false)
    const routeConfig = getRouteConfig("/shipSRM/gyszx/gys_form");
    if (routeConfig) {
      setnowroute({ 
        route: "/shipSRM/gyszx/gys_form", 
        title: "供应商档案" 
      });
    } else {
      setnowroute({ 
        route: "/shipSRM/gyszx/gys_form", 
        title: "供应商档案" 
      });
    }
  }

  const handleTaskRoute = (title, item) => {
    console.log("item选中值为===========================",item)
    
    // 任务类型到路由路径的映射
    const taskRouteMap = {
      "注册申请": {
        route: "/shipSRM/baseinfo/zcxx_form",
        storageKey: "pre_zcxx_item",
        type: "edit",
        title: "注册申请_编辑"
      },
      "供应商变更": {
        route: "/shipSRM/gyszx/gysbg_form", 
        storageKey: "pre_gysbg_item",
        type: "view",
        title: "供应商变更_查看"
      },
      "评标": {
        route: "/shipSRM/zbzx/xmpb_form",
        storageKey: "pre_xmpb_item", 
        type: "edit",
        title: "项目评标表单"
      },
      "遴选": {
        route: "/shipSRM/zbzx/xm_kb_form",
        storageKey: "pre_xm_kb_item",
        type: "edit", 
        title: "遴选_编辑"
      },
      "竞价主持": {
        route: "/shipSRM/zbzx/xm_zb_form",
        storageKey: "pre_xm_zb_item",
        type: "edit",
        title: "竞价主持_编辑"
      },
      "应标": {
        route: "/shipSRM/zbzx/gysyb_form",
        storageKey: "pre_gysyb_item",
        type: "view",
        title: "供应商应标_编辑"
      },
      "待竞标": {
        route: "/shipSRM/zbzx/gysjb_form",
        storageKey: "pre_gysjb_item",
        type: "view",
        title: "供应商竞标_查看"
      },
      "竞标中": {
        route: "/shipSRM/zbzx/gysjb_form",
        storageKey: "pre_gysjb_item",
        type: "view",
        title: "供应商竞标_查看"
      },
      "投标": {
        route: "/shipSRM/zbzx/gystb_form",
        storageKey: "pre_gystb_item",
        type: "edit",
        title: "供应商投标_编辑"
      },
      "中标确认": {
        route: "/shipSRM/zbzx/gyszb_form",
        storageKey: "pre_gyszb_item",
        type: "view",
        title: "供应商中标_查看"
      },
      "询价": {
        route: "/shipSRM/zbzx/gysxj_form",
        storageKey: "pre_gysxj_item",
        type: "view",
        title: "供应商询价_报价"
      },
      "中标分配": {
        route: "/shipSRM/zbzx/zbfp_form",
        storageKey: "pre_zbfp_item",
        type: "edit",
        title: "中标分配_查看"
      }
    };

    const taskConfig = taskRouteMap[title];
    if (taskConfig) {
      storage[taskConfig.storageKey] = JSON.stringify({ 
        data: item, 
        type: taskConfig.type 
      });
      setnowroute({ 
        route: taskConfig.route, 
        title: taskConfig.title 
      });
      // 强制跳转，确保页面刷新
      history.push(taskConfig.route);
    } else {
      openNotification_util(`未找到任务类型 "${title}" 的路由配置，请联系管理员！`);
      console.warn(`未找到任务类型 "${title}" 的路由配置`, item);
    }
  }

  const toRoute = (item) => {
    const routeConfig = getRouteConfig(item.route);
    if (routeConfig) {
      setnowroute({ 
        route: item.route, 
        title: item.cdmc || routeConfig.title 
      });
    } else {
      setnowroute({ 
        route: item.route, 
        title: item.cdmc 
      });
    }
  }

  const TabPaneItem = (title, key, dataSource, handleTaskRoute) => {
    return <Tabs.TabPane tab={<span>{title}<span style={{
      display: 'inline-block', padding: '0 6px', fontSize: '12px', lineHeight: '14px', backgroundColor: '#a90f14',
      color: 'white', borderRadius: '8px', marginLeft: '4px'
    }}>{dataSource.length}</span></span>}
      key={key} style={{ height: '300px', overflowY: 'auto' }}>
      <List
        size="small"
        style={{
          padding: '0 10px'
        }}
        dataSource={dataSource}
        renderItem={(item) => (
          <List.Item
            onClick={() => handleTaskRoute(item.rwlx, item)}
            style={{ padding: '12px 14px', background: 'white', borderRadius: '8px', margin: '8px 0', backgroundColor: "rgb(221, 221, 221)", cursor: 'pointer' }}>
            <div style={{ display: 'flex', flexDirection: 'column' }}>
              <div style={{ display: 'flex', gap: '12px', marginBottom: '8px' }}>
                <Typography.Text strong>【{item.rwlx}】</Typography.Text>
                <Typography.Text>{item.xmmc}</Typography.Text>
                <Typography.Text>{item.create_by}</Typography.Text>
                {item.rwlx == "待竞标"||item.rwlx == "竞标中" ? <Typography.Text>{item.kbsj ? "【开始时间】" + item.kbsj.substring(0, 10) + " " + item.kbsj.substring(11, 19) : "【开始时间】待定"}</Typography.Text> : null}
                
              </div>
              <div style={{ display: 'flex', gap: '12px', color: '#666' }}>
                <ClockCircleOutlined style={{ color: '#666666' }} />
                <Typography.Text style={{ color: '#666666' }}>{item.create_time.substring(0, 10)}</Typography.Text>
                <Typography.Text style={{ color: '#666666' }}>{item.create_time.substring(11, 19)}</Typography.Text>
              </div>
            </div>
          </List.Item>
        )}
      />
    </Tabs.TabPane>
  }


  return (
    <div
      style={{
        height: "100%", 
        width: "100%",
        backgroundColor: `#F1F1F1`, 
        overflow: "auto",
        fontSize: "14px",
        position: "relative"
      }}>

      <Modal open={open} title="通知公告" footer={null} onCancel={() => setOpen(false)} bodyStyle={{ width: "90vw", height: "80vh" }} width='90vw'>
        <div style={{ height: "100%", width: "100%" }} dangerouslySetInnerHTML={{ __html: previewContent }} />
      </Modal>


      <div style={{
        width: '100%', 
        height: "100%",
       
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        backgroundRepeat: 'no-repeat',
        position: "relative"
      }}>
        <div style={{ 
          height: "100%", 
          width: "100%", 
          backgroundColor: "rgba(236, 236, 236, 0.5)", 
          backdropFilter: "blur(1px)", 
          WebkitBackdropFilter: "blur(1px)",
          padding: "20px",
          boxSizing: "border-box"
        }}>
          <div style={{ 
            width: '100%', 
            height: "100%", 
            position: 'relative', 
            backgroundImage: "linear-gradient(to bottom right,rgba(255,255,255,0.1) ,rgba(255,255,255,0.1) 30%,rgba(255,255,255,0))",
            display: "flex",
            flexDirection: "column",
            gap: "20px"
          }}>

            {/* 常用功能区域 */}
            <div>
              <div style={{
                fontSize: "16px", 
                fontFamily: "'Noto Sans SC', sans-serif, Microsoft YaHei", 
                fontWeight: 600, 
                textAlign: 'left', 
                paddingLeft: '14px', 
                paddingTop: '8px', 
                paddingBottom: '8px',
                marginBottom: '14px', 
                borderLeft: '4px solid #a90f14', 
                letterSpacing: "0.05rem", 
                background: 'linear-gradient(to right, white, transparent 20%)'
              }}>
                常用功能
              </div>
              <div style={{
                width: "100%", 
                minHeight: "160px", 
                backgroundColor: "rgba(255,255,255,0.8)", 
                display: "flex",
                justifyContent: "flex-start", 
                alignItems: "center", 
                flexWrap: "wrap", 
                borderRadius: "10px",
                padding: "14px",
                gap: "12px"
              }}>
                {
                  (scList.length == 0) ?
                    <div style={{ width: "100%", height: "80px", display: "flex", justifyContent: "center", alignItems: "center", color: "#004C8B" }}>
                      <Spin /></div>
                    : scList[0].children.map((item, index) => (
                      <Button 
                        key={index}
                        className="my-button" 
                        style={{
                          height: '40px', 
                          fontSize: '14px', 
                          borderRadius: '8px', 
                          fontWeight: "400",
                          minWidth: "100px",
                          padding: "0 14px"
                        }}
                        onClick={() => toRoute(item)} 
                      >
                        {item.cdmc}
                      </Button>
                    ))
                }
              </div>
            </div>

            {/* 任务中心和通知公告区域 */}
            <div style={{ display: 'flex', gap: '20px', flex: 1, minHeight: 0 }}>
              <div style={{ flex: 1 }}>
                <div style={{
                  fontSize: "16px", 
                  fontFamily: "'Noto Sans SC', sans-serif, Microsoft YaHei", 
                  fontWeight: 600, 
                  textAlign: 'left', 
                  paddingLeft: '14px', 
                  paddingTop: '8px', 
                  paddingBottom: '8px',
                  marginBottom: '14px', 
                  borderLeft: '4px solid #a90f14', 
                  letterSpacing: "0.05rem", 
                  background: 'linear-gradient(to right, white, transparent 40%)'
                }}>
                  任务中心
                </div>
                <div style={{
                  height: "calc(100% - 48px)",
                  backgroundColor: "rgba(255,255,255,0.95)",
                  borderRadius: "10px",
                  padding: "14px"
                }}>
                  <Tabs defaultActiveKey="1" className='task-tabs' style={{ height: '100%' }}>
                    {storage.yhlx == "管理用户" ? TabPaneItem("待办", "1", glDbList, handleTaskRoute) : null}
                    {storage.yhlx == "租户用户" ? TabPaneItem("待办", "3", zhDbList, handleTaskRoute) : null}
                  </Tabs>
                </div>
              </div>
              
              <div style={{ flex: 1 }}>
                <div style={{
                  fontSize: "16px", 
                  fontFamily: "'Noto Sans SC', sans-serif, Microsoft YaHei", 
                  fontWeight: 600, 
                  textAlign: 'left', 
                  paddingLeft: '14px', 
                  paddingTop: '8px', 
                  paddingBottom: '8px',
                  marginBottom: '14px', 
                  borderLeft: '4px solid #a90f14', 
                  letterSpacing: "0.05rem", 
                  background: 'linear-gradient(to right, white, transparent 40%)'
                }}>
                  通知公告
                </div>
                <div style={{
                  height: "calc(100% - 48px)",
                  backgroundColor: "rgba(255,255,255,0.95)",
                  borderRadius: "10px",
                  padding: "14px"
                }}>
                  <List
                    size="small"
                    style={{ height: "100%", overflow: "auto" }}
                    dataSource={fbTzggList}
                    renderItem={(item) => (
                      <List.Item 
                        onClick={() => { setOpen(true); setPreviewContent(item.tznr); }}
                        style={{ cursor: 'pointer', padding: '12px 0', borderBottom: '1px solid #f0f0f0' }}
                      >
                        <div style={{ width: '100%', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                          <Typography.Text ellipsis style={{ flex: 1, marginRight: '12px' }}>{item.bt}</Typography.Text>
                          <Typography.Text type="secondary" style={{ fontSize: '12px' }}>{item.fbsj}</Typography.Text>
                        </div>
                      </List.Item>
                    )}
                  />
                </div>
              </div>
            </div>

            {/* 底部版权信息 */}
            <div style={{ 
              textAlign: 'center', 
              fontSize: "12px", 
              color: "#666", 
              padding: "14px 0",
              borderTop: "1px solid rgba(255,255,255,0.3)"
            }}>
              甬舟能源技术股份有限公司
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

export default Mainpage